import {Http} from "@angular/http";
import {BaseService} from "./base.service";
import {Injectable} from "@angular/core";
import {CacheService} from "./cache.service";
import {myValidNull} from "../util/string-utils";
import {isUndefined} from "util";
import {el} from "@angular/platform-browser/testing/src/browser_util";

/**
 * 账号管理服务
 */
@Injectable()
export class UsersService extends BaseService {

  constructor(http: Http,private cacheService:CacheService) {
    super(http)
  }

  baseUrl = "sys_users";

  /**
   * 获取用户账号列表
   *
   * @param page
   * @returns {Promise<any>}
   */
  pagination(page,keyword,status,groupId): Promise<any> {
    let url = this.baseUrl + "/pagination";
    if (!myValidNull(keyword)) {
      page['_filter_like_keyword'] = keyword
    }
    if (!isUndefined(status)) {
      page['_filter_eq_status'] = status
    }
    if (!isUndefined(groupId)) {
      page['_filter_eq_groupId'] = groupId
    }
    return this.post(url,page);
  }

  saveOrUpdateUser(user): Promise<any> {
    if(myValidNull(user.id)){
      return this.post(this.baseUrl,user);
    }else {
      return this.put(this.baseUrl+"/"+user.id,user);
    }
  }

  loadCurrentUserInfo(): Promise<any> {
    let user = this.cacheService.getCurrUserInfo();
    if(myValidNull(user)){
      let promise = this.get(this.baseUrl+"/action/getCurrUserInfo");
      promise.then((user)=>{
        this.cacheService.setCurrUserInfo(user)
      },error=>{
        console.error("获取当前用户出错：",error);
      })
      return promise;
    }else {
      return Promise.resolve(user);
    }
  }

  load(id): Promise<any> {
    return this.get(this.baseUrl+"/"+id);
  }

  deleteObj(ids): Promise<any> {
    return this.delete(this.baseUrl+"/",ids);
  }

  /**
   * 冻结用户
   * @param id
   * @returns {Promise<any>}
   */
  blocked(id): Promise<any> {
    let url = this.baseUrl+"/"+id+"/blocked";
    return this.put(url)
  }

  /**
   * 解除冻结用户
   * @param id
   * @returns {Promise<any>}
   */
  unBlocked(id): Promise<any> {
    let url = this.baseUrl+"/"+id+"/un_blocked";
    return this.put(url)
  }

  /**
   * 管理员重置密码
   *
   * @param id
   * @returns {Promise<any>}
   */
  resetPassword(id): Promise<any> {
    let url = this.baseUrl+"/"+id+"/reset_password";
    return this.put(url)
  }

  /**
   * 当前用户修改密码
   * @param id
   * @returns {Promise<any>}
   */
  modifyPassword(password): Promise<any> {
    let url = this.baseUrl+"/modify_password";
    return this.put(url,password)
  }

}
